package lol.clann.minecraft.springboot.plugin.core;

import com.google.auto.service.AutoService;
import com.ruoshui.utils.java.exception.ExceptionUtils;
import lol.clann.minecraft.springboot.api.model.core.Plugin;
import lol.clann.minecraft.springboot.api.spi.sbp.ApplicationRunListener;
import lol.clann.minecraft.springboot.api.context.PluginContext;
import lol.clann.minecraft.springboot.plugin.core.model.PluginConfigPropertySouce;
import lombok.extern.slf4j.Slf4j;
import okio.Okio;
import org.springframework.boot.SpringApplication;
import org.springframework.core.env.ConfigurableEnvironment;

import java.io.IOException;

/**
 * 将插件配置文件作为propertySource添加到springContext
 *
 * @author pyz
 * @date 2019/6/22 5:25 PM
 */
@Slf4j
@AutoService(ApplicationRunListener.class)
public class PluginConfigPropertySouceSupplier implements ApplicationRunListener {

    @Override
    public void environmentPrepared(SpringApplication application, ConfigurableEnvironment environment) {
        for (Plugin plugin : PluginContext.getPlugins()) {
            environment.getPropertySources().addLast(new PluginConfigPropertySouce(plugin));
        }
        String debugConfig = environment.getProperty("springbootplugin.debug.config", "false");
        if (Boolean.valueOf(debugConfig)) {
            LOGGER.warn("配置文件调试模式处于开始状态,将打印所有SBP插件配置文件内容...");
            for (Plugin plugin : PluginContext.getPlugins()) {
                LOGGER.warn(plugin.getDisplayName() + ": " + plugin.getConfig().toAbsolutePath().toString());
                try {
                    String content = Okio.buffer(Okio.source(plugin.getConfig().toFile())).readUtf8();
                    LOGGER.info(content);
                } catch (IOException e) {
                    ExceptionUtils.throwException(e);
                }
            }
        }
    }
}
